"""
数据存储管理模块 - 负责数据的持久化存储
作者：E同学
功能：
1. 加载物品数据
2. 保存物品数据
3. 管理商品ID顺序
"""

import json
import os

# 确保数据目录存在
if not os.path.exists('data'):
    os.makedirs('data')

# 数据文件路径
ITEMS_FILE_PATH = 'data/items.json'
# ID计数器文件路径
ID_COUNTER_FILE = 'data/id_counter.json'


def load_id_counter():
    """加载ID计数器"""
    try:
        if os.path.exists(ID_COUNTER_FILE):
            with open(ID_COUNTER_FILE, 'r', encoding='utf-8') as file:
                return json.load(file).get('next_id', 1)
        return 1
    except:
        return 1


def save_id_counter(next_id):
    """保存ID计数器"""
    try:
        with open(ID_COUNTER_FILE, 'w', encoding='utf-8') as file:
            json.dump({'next_id': next_id}, file, ensure_ascii=False, indent=2)
    except Exception as e:
        print(f"\033[1;31m⚠️ 保存ID计数器时出错: {e}")


# E同学负责的函数
def load_all_items_from_file():
    """加载所有物品数据"""
    try:
        if not os.path.exists(ITEMS_FILE_PATH):
            return []

        with open(ITEMS_FILE_PATH, 'r', encoding='utf-8') as file:
            items = json.load(file)
            # 确保每个物品都有item_id字段
            for item in items:
                if 'item_id' not in item:
                    # 如果缺少ID，使用当前计数器值并递增
                    next_id = load_id_counter()
                    item['item_id'] = next_id
                    save_id_counter(next_id + 1)
            return items
    except FileNotFoundError:
        print("\033[1;33m💡 未找到数据文件，将创建新的空文件")
        return []
    except json.JSONDecodeError:
        print("\033[1;31m⚠️ 数据文件损坏，将创建新文件")
        return []
    except Exception as e:
        print(f"\033[1;31m⚠️ 加载数据时出错: {e}")
        return []


def get_next_item_id():
    """获取下一个可用的物品ID"""
    next_id = load_id_counter()
    save_id_counter(next_id + 1)
    return next_id


def save_item_to_file(new_item_dict):
    """保存新物品到文件"""
    items = load_all_items_from_file()
    # 添加顺序ID
    new_item_dict['item_id'] = get_next_item_id()
    items.append(new_item_dict)
    _save_all_items(items)


# E同学负责的函数
def update_item_in_file(updated_item_dict):
    """更新物品信息"""
    items = load_all_items_from_file()
    for i, item in enumerate(items):
        if item['item_id'] == updated_item_dict['item_id']:
            items[i] = updated_item_dict
            _save_all_items(items)
            print("\033[1;32m💾 物品信息已更新！")
            return
    print("\033[1;31m⚠️ 未找到对应物品，更新失败")


def _save_all_items(items):
    """内部方法：保存所有物品"""
    try:
        with open(ITEMS_FILE_PATH, 'w', encoding='utf-8') as file:
            json.dump(items, file, ensure_ascii=False, indent=2)
        print("\033[1;32m💾 数据已成功保存！")
    except Exception as e:
        print(f"\033[1;31m⚠️ 保存数据时出错: {e}")